package com.juzipi.demo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.juzipi.demo.pojo.Student;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Author juzipi
 * @Date 2021/4/30 16:10
 * @Info
 */
@RestController
@RequestMapping("student")
public class StudentController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 条件查询
     * @param id
     * @return
     */
    @GetMapping("get")
    public Object get(@RequestParam String id){
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.where("_id").is(id);
        query.addCriteria(criteria);
        //根据id查询
        Student student = mongoTemplate.findById(id, Student.class);
        System.out.println(student);

        return mongoTemplate.find(query, Student.class);
    }


    //大功告成，是这样的，mongodb是可以创建管理员用户和普通用户，新创建普通用户可以指定它的权限和所管理的库，
    //必须要在 新建的用户 所要管理的库里 创建这个用户才行
    @GetMapping("list")
    public List<Student> get(){
        List<Student> students = mongoTemplate.findAll(Student.class);
        return students;
    }



    /**
     * 模糊查询，写法之一
     * @param key
     * @return
     */
    @PostMapping("like")
    public List<Student> like(@RequestParam String key){
        //模糊全匹配 类似于：% key %
        Pattern compile = Pattern.compile("^.*" + key + ".*$");

//        String format = String.format("%s%s%s", "^.*", key, ".*$");
//        Pattern pattern = Pattern.compile(format, Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("name").regex(compile));

        System.out.println(query);
        return mongoTemplate.find(query, Student.class);
    }


    @PostMapping("page")
    public Map<String,Object> page(
            @RequestParam(value = "key") String key,
            @RequestParam(value = "pageNum", defaultValue ="1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
                                   ){
        Pattern compile = Pattern.compile("^.*" + key + ".*$");
        //想加一个or条件，但是不行
        //.orOperator(Criteria.where("gender").regex(compile))
        Query query = new Query(Criteria.where("name").regex(compile));
        System.out.println(query);
        //它的下一条语句会分页，详情看pageHelper文档
        PageHelper.startPage(pageNum,pageSize);
        List<Student> students = mongoTemplate.find(query, Student.class);
        students.forEach(student -> System.out.println(student.getName()));
        //第二个参数为默认页数
        PageInfo<Student> studentPageInfo = new PageInfo<>(students, 1);

        LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("当前页: ",studentPageInfo.getPageNum());
        linkedHashMap.put("页面大小: ", studentPageInfo.getPageSize());
        linkedHashMap.put("数据条数: ", studentPageInfo.getTotal());
        linkedHashMap.put("数据集: ",studentPageInfo.getList());
        return linkedHashMap;
    }


    /**
     * 新增
     * @param student
     * @return
     */
    @PostMapping("insert")
    public Boolean insert(@RequestBody Student student){
        Student insert = mongoTemplate.insert(student);
        return !StringUtils.isEmpty(insert.getId());
    }

    /**
     * 更新
     * @param student
     * @return
     */
    @PutMapping("update")
    public Boolean update(@RequestBody Student student){
        /*
        query相当于是mysql更新是的where，就是条件
        update就是mongo的更新语句了，打印如下:
        { "$set" : { "name" : "李子明明", "age" : 27, "gender" : "男"}}
        值就是字段名和值的键值对，最后一个参数是实体类class
         */
        Query query = new Query(Criteria.where("_id").is(student.getId()));
        System.out.println("条件==================="+query);
        Update update = new Update();
        update.set("name",student.getName());
        update.set("age",student.getAge());
        update.set("gender",student.getGender());

        System.out.println("================================"+update);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
        long modifiedCount = updateResult.getModifiedCount();
        return modifiedCount>0;
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("del/{id}")
    public Boolean delete(@PathVariable Long id){
        //转一下类型，id是String类型的
        String s = String.valueOf(id);
        Query query = new Query(Criteria.where("_id").is(s));
        System.out.println(query);
        DeleteResult deleteResult = mongoTemplate.remove(query, Student.class);
        long deletedCount = deleteResult.getDeletedCount();
        return deletedCount>0;
    }




}
